package com.jurenzhao.partssystem.system.system_log.util;

import com.jurenzhao.partssystem.system.system_log.service.LogService;

import javax.annotation.Resource;
import com.jurenzhao.partssystem.system.system_log.aspect.annotation.SystemControllerLog;
import com.jurenzhao.partssystem.system.system_log.aspect.annotation.SystemServiceLog;
import com.jurenzhao.partssystem.system.system_log.entity.System_Log;
import com.jurenzhao.partssystem.system.system_log.service.LogService;
import com.jurenzhao.partssystem.system.system_user.entity.System_Users;
import com.jurenzhao.partssystem.system.system_user.service.System_UserService;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class MyLog {


    //注入Service用于把日志保存数据库
    @Resource
    private LogService logService;

    @Resource()
    private System_UserService system_userService;

    @Resource
    SqlSessionFactory sqlSessionFactory;


    //本地异常日志记录对象
  //  private final static Logger logger = Logger.getLogger(SystemLogAspect.class);

    //@Transactional
    public void beforeLog(JoinPoint joinPoint) {
        System.out.println("MyLog -- ：" + joinPoint.getSignature().getName() + " 方法开始执行...");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        String user_no = (String) session.getAttribute("user_no");
        System_Users system_users = system_userService.findByNo(user_no);
        System.out.println("session loginUser " + session.getAttribute("loginUser"));
        //String userName = (System_Users) session.getAttribute("System_Users") == null ? "" : ((System_Users) session.getAttribute("System_Users")).getUserName();
//        System_Users system_users = (System_Users) session.getAttribute("System_Users");
//        String userName = system_users.getUserName();
        String userName = (System_Users) session.getAttribute("System_Users") == null ?
                "" : ((System_Users) session.getAttribute("System_Users")).getUserName();
        //请求的IP
        String ip = Constants.getIpAddr(request);
        System.out.println("请求方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
        System.out.println("请求IP:" + ip);
        System.out.println("请求人:" + userName);
        System_Log system_log = new System_Log();
        system_log.setLogUser(system_users.getUserName());
        system_log.setLogType("0");
        //log.setLogMName((joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
        system_log.setLogDate(new Date());
        system_log.setLogIp(ip);
        //0是登录，1是登出，2是添加，3是删除，4是修改
        if(joinPoint.getSignature().getName().startsWith("login")){
            system_log.setLogState("0");
        }else if (joinPoint.getSignature().getName().startsWith("save")){
            system_log.setLogState("2");
            system_log.setLogInfo("修改了数据库");
        }else if (joinPoint.getSignature().getName().startsWith("update")){

            system_log.setLogState("4");
            system_log.setLogInfo("修改了数据库");
        }else if (joinPoint.getSignature().getName().startsWith("delete")){
            system_log.setLogState("3");
            system_log.setLogInfo("修改了数据库");
        }else{
            system_log.setLogState("1");
        }
        ////保存数据库
        logService.insert(system_log);
        System.out.println("===== 本次前置通知结束 ======");
    }

    public void afterLog(JoinPoint jp) {
        System.out.println("MyLog -- ：" + jp.getSignature().getName() + " 方法执行结束...");
    }

    /**
     * 获取注解中对方法的描述信息 用于service层注解
     *
     * @param joinPoint 切点
     * @return 方法描述
     * @throws Exception
     */
    public static String getServiceMthodDescription(JoinPoint joinPoint)
            throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    description = method.getAnnotation(SystemServiceLog. class).description();
                    break;
                }
            }
        }
        return description;

    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param joinPoint 切点
     * @return 方法描述
     * @throws Exception
     */

    public static String getControllerMethodDescription(JoinPoint joinPoint)  throws Exception {
        System.out.println("进入了 getControllerMethodDescription 方法");
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    description = method.getAnnotation(SystemControllerLog. class).description();
                    break;
                }
            }
        }
        return description;
    }
}
